package serverdata.ch.home.www.ResponseClass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import serverdata.ch.home.www.server.HttpData;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.util.Log;

public class GetAllSensorExistingResponse {

	private SensorManager sm;

	public GetAllSensorExistingResponse(PrintWriter out, BufferedReader in, SensorManager sm, HttpData inputhttp) throws IOException {

		System.out.println("entro");

		this.sm = sm;

		HashMap<String, String> params = inputhttp.getParametri();

		String type = params.get("TYPE");

		String data;

		if(type != null && type.equalsIgnoreCase("html")){
			data = htmldata();
		}else if(type != null && type.equalsIgnoreCase("xml")){
			data = XMLdata();
		}
		else{
			data = JSONdata();
		}

		out.print(HttpData.createHeaderHTTP(data, 200, type));

		out.print(data+"\r\n");
		out.flush();
		out.close();
		in.close();




	}

	private String htmldata(){

		List<Sensor> list = sm.getSensorList(Sensor.TYPE_ALL);
		List<String> sensorname = IndexPage.getSensorName(sm);
		StringBuilder data = new StringBuilder();
		data.append("<html><title>Dati andorid</title><body>");
		for(int i = 0; i<list.size(); i++){
			data.append("<p>");
			data.append("name: "+list.get(i).getName());
			data.append("   ");
			data.append("type: "+"<a href=\"sensorvalues?sensore="+sensorname.get(i)+"\">link</a>" );
			data.append("</p>");
		}

		data.append("</body></html>");

		return data.toString();

	}

	private String JSONdata(){

		JSONArray array = new JSONArray();
		try{
			List<Sensor> list = sm.getSensorList(Sensor.TYPE_ALL);
			List<String> sensorname = IndexPage.getSensorName(sm);
			

			JSONObject obj;


			for(int i = 0; i<list.size(); i++){
				obj = new JSONObject();
				obj.put("name", list.get(i).getName());
				obj.put("link", "sensorvalues?sensore="+sensorname.get(i));
				array.put(obj);
			}


		}catch(JSONException e){
			Log.e("AllSensorExisting", "errore nella creazione del JSON", e);
		}

		return array.toString();
	}
	private String XMLdata(){
		
		StringBuilder data = new StringBuilder();
		
		List<Sensor> list = sm.getSensorList(Sensor.TYPE_ALL);
		List<String> sensorname = IndexPage.getSensorName(sm);
		data.append("<?xml version=\"1.0\"?>");
		data.append("<listasensore>");
		for(int i = 0; i<list.size(); i++){
			data.append("<sensore><nome>"+list.get(i).getName()+"</nome>");
			data.append("<link>sensorvalues?sensore="+sensorname.get(i)+"</link></sensore>");
		}
		data.append("</listasensore>");
		
		return data.toString();
		
		
	}
}
